Telegram Group & Telegram Channel
Note #32 negative slice/array indexes

Уже несколько раз попадается на глаза противоречивое предложение добавить в Go отрицательные индексы как в Python. Те сейчас негативные индексы вызывают панику:
func main() {
a := []int{1, 2, 3}
fmt.Println(a[-1])
}
invalid slice index -1 (index must be non-negative)

А чтобы взять последний элемент slice’а, нужно написать так:
func main() {
a := []int{1, 2, 3}
fmt.Println(a[len(a)-1])
}

В Go 2 было предложено очередной раз добавить:
a := m[-3]
// is equivalent to
a := m[len(m)-3]

Идея не увенчалась успехом, хотя по-мнению автора это добавляет читаемость кода, что довольно спорно.
Но зато в комментариях я нашел другое предложение от Ian Lance Taylor:
> Использовать len без скобок для того чтобы получить последний элемент слайса:
a := m[len-1]

Эту идею многие поддержали… но пока ни к чему не пришли.
P.S. Касательно -1 и других языков программирования: хотя и в Python -1 означает len - 1 в контексте индексов списков, в JavaScript -1 всего лишь -1, а в Java - это IndexOutOfBounds. Поэтому с точки зрения читаемости кода len-1 самый понятный.
to be continued…
Links:
https://github.com/golang/go/issues/33359
https://github.com/golang/go/issues/16231
https://github.com/golang/go/issues/20176
https://github.com/golang/go/issues/11245



tg-me.com/golang_for_two/57
Create:
Last Update:

Note #32 negative slice/array indexes

Уже несколько раз попадается на глаза противоречивое предложение добавить в Go отрицательные индексы как в Python. Те сейчас негативные индексы вызывают панику:

func main() {
a := []int{1, 2, 3}
fmt.Println(a[-1])
}
invalid slice index -1 (index must be non-negative)

А чтобы взять последний элемент slice’а, нужно написать так:
func main() {
a := []int{1, 2, 3}
fmt.Println(a[len(a)-1])
}

В Go 2 было предложено очередной раз добавить:
a := m[-3]
// is equivalent to
a := m[len(m)-3]

Идея не увенчалась успехом, хотя по-мнению автора это добавляет читаемость кода, что довольно спорно.
Но зато в комментариях я нашел другое предложение от Ian Lance Taylor:
> Использовать len без скобок для того чтобы получить последний элемент слайса:
a := m[len-1]

Эту идею многие поддержали… но пока ни к чему не пришли.
P.S. Касательно -1 и других языков программирования: хотя и в Python -1 означает len - 1 в контексте индексов списков, в JavaScript -1 всего лишь -1, а в Java - это IndexOutOfBounds. Поэтому с точки зрения читаемости кода len-1 самый понятный.
to be continued…
Links:
https://github.com/golang/go/issues/33359
https://github.com/golang/go/issues/16231
https://github.com/golang/go/issues/20176
https://github.com/golang/go/issues/11245

BY 🇺🇦 Go for two :)


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/golang_for_two/57

View MORE
Open in Telegram


🇺🇦 Go на двоих Telegram | DID YOU KNOW?

Date: |

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

What is Telegram?

Telegram’s stand out feature is its encryption scheme that keeps messages and media secure in transit. The scheme is known as MTProto and is based on 256-bit AES encryption, RSA encryption, and Diffie-Hellman key exchange. The result of this complicated and technical-sounding jargon? A messaging service that claims to keep your data safe.Why do we say claims? When dealing with security, you always want to leave room for scrutiny, and a few cryptography experts have criticized the system. Overall, any level of encryption is better than none, but a level of discretion should always be observed with any online connected system, even Telegram.

🇺🇦 Go на двоих from us


Telegram 🇺🇦 Go for two :)
FROM USA